package com.mf.morefun.ui.moreread;

import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.adapter.MyAdapter;
import com.mf.morefun.adapter.TestListenSelectCharAdapter;
import com.mf.morefun.adapter.TestListenSelectPicAdapter;
import com.mf.morefun.adapter.TestPicSelectAdapter;
import com.mf.morefun.adapter.TestTextAdapter;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.bean.TestBean;
import com.mf.morefun.bean.WordBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.listener.MyRequestListener;
import com.mf.morefun.listener.OnStartDragListener;
import com.mf.morefun.listener.ReadDetailTypeListener;
import com.mf.morefun.requestbean.RequestTestTimeBean;
import com.mf.morefun.service.MusicTestService;
import com.mf.morefun.ui.userinfo.LoginActivity;
import com.mf.morefun.util.GetUserInfo;
import com.mf.morefun.util.IsLoginBean;
import com.mf.morefun.util.ListViewUtil;
import com.mf.morefun.util.SendStarOrFlowerNet;
import com.mf.morefun.util.TransformationUtils;
import com.mf.morefun.widget.BackIdeaPop;
import com.mf.morefun.widget.DividerGridItemDecoration;
import com.mf.morefun.widget.NetErrorPop;
import com.mf.morefun.widget.NoScrollGridView;
import com.mf.morefun.widget.PicDividerGridItemDecoration;
import com.mf.morefun.widget.SwipeRecyclerView;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.DeviceUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DoTestActivity extends BaseBusActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.rv_mftestlistenselectpic)
    RecyclerView rvMftestlistenselectpic;
    @BindView(R.id.iv_mftestlistenselectpic)
    ImageView ivMftestlistenselectpic;
    @BindView(R.id.ll_mftestlistenselectpics)
    LinearLayout llMftestlistenselectpics;
    @BindView(R.id.ll_mftestlistenselectpic)
    RelativeLayout llMftestlistenselectpic;
    @BindView(R.id.iv_mftestlistenselectcharbg)
    ImageView ivMftestlistenselectcharbg;
    @BindView(R.id.iv_mftestlistenselectchar)
    ImageView ivMftestlistenselectchar;
    @BindView(R.id.tv_char)
    TextView tvChar;
    @BindView(R.id.tv_needchar)
    TextView tvNeedchar;
    @BindView(R.id.tv_chartwo)
    TextView tvChartwo;
    @BindView(R.id.gv_mftestlistenselectchar)
    NoScrollGridView gvMftestlistenselectchar;
    @BindView(R.id.ll_mftestlistenselectchar)
    LinearLayout llMftestlistenselectchar;
    @BindView(R.id.tv_mftesttextselect)
    TextView tvMftesttextselect;
    @BindView(R.id.gv_mftesttextselect)
    NoScrollGridView gvMftesttextselect;
    @BindView(R.id.ll_mftesttextselect)
    LinearLayout llMftesttextselect;
    @BindView(R.id.iv_headbg)
    ImageView ivHeadbg;
    @BindView(R.id.tv_picselectname)
    TextView tvPicselectname;
    @BindView(R.id.ll_listentext)
    LinearLayout llListentext;
    @BindView(R.id.lv_mftestpicselect)
    ListView lvMftestpicselect;
    @BindView(R.id.ll_mftestpicselect)
    LinearLayout llMftestpicselect;
    @BindView(R.id.recyclerView)
    SwipeRecyclerView recyclerView;
    @BindView(R.id.iv_success)
    ImageView ivSuccess;
    @BindView(R.id.iv_mftestlistenword)
    ImageView ivMftestlistenword;
    @BindView(R.id.ll_mftestlistenword)
    LinearLayout llMftestlistenword;
    @BindView(R.id.pb_speed)
    ProgressBar pbSpeed;
    @BindView(R.id.iv_successgif)
    ImageView ivSuccessgif;
    @BindView(R.id.ly_content)
    LinearLayout lyContent;
    @BindView(R.id.rl_bg)
    RelativeLayout rlBg;
    private int currentPosition = 0;
    private MusicTestService mMusicTestService = null;
    private MediaPlayer mp;
    private String picSelectUrl = "";
    private SPUtils mSPutils;
    private List<WordBean> mWordBeanList = new ArrayList<>();//这是打乱的
    private MyAdapter myAdapter;
    private ItemTouchHelper mItemTouchHelper;
    private SendStarOrFlowerNet mSendStartOrFlowerNet;


    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_dotest;
    }


    /**
     * 1、mfTestListenSelectPic 听声音选择图片
     * 2、mfTestListenSelectChar 听声音选择字母
     * 3、mfTestTextSelect 文字选择题
     * 4、mfTestListenWord 听声音拼单词
     * 5、mfTestPicSelect 图片选择题
     *
     * @param savedInstanceState
     */
    @Override
    protected void initView(Bundle savedInstanceState) {
        mSPutils = new SPUtils(getApplicationContext());
        if (!IsLoginBean.isNo(false)) {
            GetUserInfo.initLogin(mSPutils.getString(Configuration.USERPHONE), mSPutils.getString(Configuration.USERPASSWORD));
        }
        if (null != MoreFunApplication.mTestList && MoreFunApplication.mTestList.size() > 0) {
            ivSuccessgif.setVisibility(View.GONE);
            Glide.with(DoTestActivity.this).asGif().load(R.mipmap.happy).into(ivSuccessgif);
            selectUi(MoreFunApplication.mTestList, currentPosition, MoreFunApplication.mTestList.size());
            //开始计时
            startTime();
        }
    }

    private int second = 0;
    private boolean isBreak = false;

    private void startTime() {
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    if (isBreak) {
                        break;
                    }
                    try {
                        second++;
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    private void setProgressBar(int currentPosition, int totalPage) {
        int index = (100 / totalPage);
        if (currentPosition == (totalPage - 1)) {
            pbSpeed.setProgress(100);
        } else {
            pbSpeed.setProgress(index * (currentPosition + 1));
        }
    }

    private void selectUi(List<TestBean> mTestList, int position, int size) {
        setProgressBar(position, size);
        if (null != mTestList.get(position).getMfTestListenSelectPic()) {//听声音选择图片
            tvTitle.setText("听声音选择图片");
            rlBg.setBackgroundResource(R.color.white);
            testListenSelectPic(mTestList, position, size);
            return;
        } else if (null != mTestList.get(position).getMfTestListenSelectChar()) {//听声音选择字母
            tvTitle.setText("听声音选择字母");
            rlBg.setBackgroundResource(R.color.test_bg);
            testListenSelectChar(mTestList, position, size);
            return;
        } else if (null != mTestList.get(position).getMfTestTextSelect()) {//文字选择题
            tvTitle.setText("文字选择题");
            rlBg.setBackgroundResource(R.color.test_bg);
            testTextSelect(mTestList, position, size);
            return;
        } else if (null != mTestList.get(position).getMfTestListenWord()) {//听声音拼单词
            tvTitle.setText("字母拼单词");
            rlBg.setBackgroundResource(R.color.test_bg);
            testListenWord(mTestList, position, size);
            return;
        } else if (null != mTestList.get(position).getMfTestPicSelect()) {//图片选择题
            tvTitle.setText("图片选择题");
            rlBg.setBackgroundResource(R.color.test_bg);
            testPicSelect(mTestList, position, size);
            return;
        } else {
            tvTitle.setText("没有测题可以做！");
            ToastUtils.show(DoTestActivity.this, "没有测题可以做！", 100);
        }
    }

    //图片选择题
    private void testPicSelect(List<TestBean> mTestList, int mPosition, int size) {
        changeUi(4);
        x.image().bind(ivHeadbg, mTestList.get(mPosition).getMfTestPicSelect().getImg());
        tvPicselectname.setText(mTestList.get(mPosition).getMfTestPicSelect().getName());
        picSelectUrl = mTestList.get(mPosition).getMfTestPicSelect().getAudio();
        List<String> wordList = new ArrayList<>();
        wordList.add(mTestList.get(mPosition).getMfTestPicSelect().getAnswerA());
        wordList.add(mTestList.get(mPosition).getMfTestPicSelect().getAnswerB());
        wordList.add(mTestList.get(mPosition).getMfTestPicSelect().getAnswerC());
        wordList.add(mTestList.get(mPosition).getMfTestPicSelect().getAnswerD());
        String audio[] = new String[4];
        audio[0] = mTestList.get(mPosition).getMfTestPicSelect().getAnswerAAudio();
        audio[1] = mTestList.get(mPosition).getMfTestPicSelect().getAnswerBAudio();
        audio[2] = mTestList.get(mPosition).getMfTestPicSelect().getAnswerCAudio();
        audio[3] = mTestList.get(mPosition).getMfTestPicSelect().getAnswerDAudio();
        TestPicSelectAdapter adapter = new TestPicSelectAdapter(DoTestActivity.this, wordList);
        lvMftestpicselect.setAdapter(adapter);
        Message message = new Message();
        message.what = 100;
        message.obj = adapter;
        mHandler.sendMessageDelayed(message, 500);
        adapter.setListener(new ReadDetailTypeListener() {//播放
            @Override
            public void callBack(int position) {
                if (null != mMusicTestService && null != mMusicTestService.player) {
                    mMusicTestService.stop();
                    mMusicTestService = new MusicTestService(audio[position], DoTestActivity.this);
                    if (!mMusicTestService.player.isPlaying()) {
                        if (null != mp) {
                            mp.stop();
                            mp.reset();
                            mp.release();
                        }
                        mMusicTestService.play();
                    } else {
                        mMusicTestService.pause();
                    }
                }
            }
        });
        lvMftestpicselect.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (((position + 1) + "").equals(mTestList.get(mPosition).getMfTestPicSelect().getAnswerKey())) {//答对
                    playMusicFromLocal(R.raw.sure, true, mPosition, size, mTestList);
                    //弹出个显示gif图的
                    ivSuccessgif.setVisibility(View.VISIBLE);
                } else {
                    playMusicFromLocal(R.raw.fail, false, mPosition, size, mTestList);
                }
            }
        });
    }

    //听声音拼单词
    private void testListenWord(List<TestBean> mTestList, int mPosition, int size) {
        changeUi(3);
        String name = mTestList.get(mPosition).getMfTestListenWord().getName();
        String image = mTestList.get(mPosition).getMfTestListenWord().getImg();
        if (null != mMusicTestService && null != mMusicTestService.player) {
            mMusicTestService.stop();
        }
        mMusicTestService = new MusicTestService(mTestList.get(mPosition).getMfTestListenWord().getAudio(), DoTestActivity.this);
        List<String> mWordList = new ArrayList<>();
        if (!StringUtils.isEmpty(name)) {
            char wordArray[] = name.toCharArray();
            for (int i = 0; i < wordArray.length; i++) {
                mWordList.add(String.valueOf(wordArray[i]));
            }
        }
        if (mWordList.size() > 0) {
            int mWordArray[] = new int[mWordList.size()];
            getTrueArray(mWordList, mWordArray);
            //打乱顺序
            Collections.shuffle(mWordList);
            //先组装一个list把是否去掉的标识加上
            mWordBeanList.clear();
            for (int i = 0; i < mWordList.size(); i++) {
                WordBean mWordBean = new WordBean();
                mWordBean.setImageId(getResources().getIdentifier(mWordList.get(i), "mipmap", getPackageName()));
                mWordBean.setSure(false);
                mWordBean.setBg(true);
                mWordBeanList.add(mWordBean);
            }
            for (int i = 0; i < mWordList.size(); i++) {
                WordBean mWordBean = new WordBean();
                mWordBean.setImageId(getResources().getIdentifier(mWordList.get(i), "mipmap", getPackageName()));
                mWordBean.setSure(true);
                mWordBean.setBg(false);
                mWordBeanList.add(mWordBean);
            }
            if (mWordBeanList.size() > 0) {
                //展示下面的view
                showBottomView(mWordBeanList, mWordArray, image, mPosition, size, mTestList);
            }
        } else {
            //关闭图片  并走下一个
            ivSuccessgif.setVisibility(View.GONE);
            currentPosition = selectIndex(mPosition, size);
            if (currentPosition == -1) {
                initPostTime(mTestList, currentPosition);
            } else {
                selectUi(mTestList, currentPosition, size);
            }
        }
    }

    private void getTrueArray(List<String> mWordList, int mWordArray[]) {
        for (int i = 0; i < mWordList.size(); i++) {
            mWordArray[i] = getResources().getIdentifier(mWordList.get(i), "mipmap", getPackageName());
        }
    }

    //展示适配器
    private void showBottomView(List<WordBean> mWordBeanList, int mWordArray[], String image, int position, int size, List<TestBean> mTestList) {
        recyclerView.removeAllViews();
        recyclerView.setLayoutManager(new GridLayoutManager(this, (mWordBeanList.size() / 2)));
        recyclerView.addItemDecoration(new DividerGridItemDecoration(this));
        myAdapter = new MyAdapter(mWordBeanList, DoTestActivity.this);
        recyclerView.setAdapter(myAdapter);
        myAdapter.setmDragStartListener(new OnStartDragListener() {
            @Override
            public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
                if (viewHolder.getLayoutPosition() >= (mWordBeanList.size() / 2)) {
                    if (null != mItemTouchHelper) {
                        mItemTouchHelper.startDrag(viewHolder);
                    }

                    //获取系统震动服务
                    Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);//震动70毫秒
                    vib.vibrate(70);

                }
            }
        });

        mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN
                            | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    final int swipeFlags = 0;
                    return makeMovementFlags(dragFlags, swipeFlags);
                } else {
                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                    final int swipeFlags = 0;
//                    final int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
                    return makeMovementFlags(dragFlags, swipeFlags);
                }
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                //得到当拖拽的viewHolder的Position
                int fromPosition = viewHolder.getAdapterPosition();
                //拿到当前拖拽到的item的viewHolder
                int toPosition = target.getAdapterPosition();
                //这个时候就该判断了
                if (toPosition <= (mWordBeanList.size() / 2)) {
                    //这里通过内容去获取正确的下标
                    if (toPosition == getTruePosition(fromPosition, mWordBeanList, mWordArray)) {
                        int imageId = 0;
                        boolean isbg = false;
                        boolean isSure = false;
                        imageId = mWordBeanList.get(fromPosition).getImageId();
                        isbg = mWordBeanList.get(fromPosition).isBg();
                        isSure = mWordBeanList.get(fromPosition).isSure();
                        mWordBeanList.get(fromPosition).setSure(mWordBeanList.get(toPosition).isSure());
                        mWordBeanList.get(fromPosition).setBg(mWordBeanList.get(toPosition).isBg());
                        mWordBeanList.get(fromPosition).setImageId(mWordBeanList.get(toPosition).getImageId());
                        mWordBeanList.get(toPosition).setImageId(imageId);
                        mWordBeanList.get(toPosition).setBg(isbg);
                        mWordBeanList.get(toPosition).setSure(isSure);
                        myAdapter.notifyDataSetChanged();
                    }
                }
                //进来一次就判断一次， 如果都完美了那么先把图片展示出来
                if (caluateAllSuccess(mWordArray, mWordBeanList)) {
                    ivSuccess.setVisibility(View.VISIBLE);
                    ivSuccessgif.setVisibility(View.VISIBLE);
                    ImageOptions imageOptions = new ImageOptions.Builder().setFailureDrawableId(R.mipmap.mf_logo).build();
                    x.image().bind(ivSuccess, image, imageOptions);
                    playMusicFromLocal(R.raw.sure, true, position, size, mTestList);
                } else {
                    ivSuccessgif.setVisibility(View.GONE);
                    ivSuccess.setVisibility(View.GONE);
                }
                return true;
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

            }

            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                    viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
                }
                super.onSelectedChanged(viewHolder, actionState);
            }

            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                viewHolder.itemView.setBackgroundColor(0);
            }
        });
        mItemTouchHelper.attachToRecyclerView(recyclerView);
    }

    private boolean caluateAllSuccess(int[] mWordArray, List<WordBean> mWordBeanList) {
        boolean isTrue = true;
        if (null != mWordArray && null != mWordBeanList && mWordArray.length > 0 && mWordBeanList.size() > 0 && mWordArray.length < mWordBeanList.size()) {
            for (int i = 0; i < mWordArray.length; i++) {
                if (mWordArray[i] != mWordBeanList.get(i).getImageId() || !mWordBeanList.get(i).isSure()) {
                    isTrue = false;
                }
            }
        } else {
            isTrue = false;
        }
        return isTrue;
    }

    private int getTruePosition(int fromPosition, List<WordBean> mWordBeanList, int[] mWordArray) {
        int position = 0;
        if (null != mWordArray && mWordArray.length > 0) {
            for (int i = 0; i < mWordArray.length; i++) {
                if (mWordBeanList.get(fromPosition).getImageId() == mWordArray[i]) {
                    position = i;
                }
            }
        }
        return position;
    }

    //文字选择题
    private void testTextSelect(List<TestBean> mTestList, int mPosition, int size) {
        changeUi(2);
        tvMftesttextselect.setText(mTestList.get(mPosition).getMfTestTextSelect().getName());
        List<String> wordList = new ArrayList<>();
        wordList.add(mTestList.get(mPosition).getMfTestTextSelect().getAnswerA());
        wordList.add(mTestList.get(mPosition).getMfTestTextSelect().getAnswerB());
        wordList.add(mTestList.get(mPosition).getMfTestTextSelect().getAnswerC());
        wordList.add(mTestList.get(mPosition).getMfTestTextSelect().getAnswerD());
        TestTextAdapter adapter = new TestTextAdapter(DoTestActivity.this, wordList);
        gvMftesttextselect.setAdapter(adapter);
        gvMftesttextselect.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (((position + 1) + "").equals(mTestList.get(mPosition).getMfTestTextSelect().getAnswerKey())) {//答对
                    playMusicFromLocal(R.raw.sure, true, mPosition, size, mTestList);
                    //弹出个显示gif图的
                    ivSuccessgif.setVisibility(View.VISIBLE);
                } else {
                    playMusicFromLocal(R.raw.fail, false, mPosition, size, mTestList);
                }
            }
        });
    }

    //听声音选择字母
    private void testListenSelectChar(List<TestBean> mTestList, int mPosition, int size) {
        changeUi(1);
        RoundedCorners roundedCorners = new RoundedCorners(DeviceUtils.dip2px(mContext, 1));
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
        Glide.with(DoTestActivity.this).asBitmap().load(mTestList.get(mPosition).getMfTestListenSelectChar().getImg()).listener(new MyRequestListener(ivMftestlistenselectcharbg, DoTestActivity.this, DeviceUtils.dip2px(mContext, 298), DeviceUtils.dip2px(DoTestActivity.this, 90))).apply(options).into(new TransformationUtils(ivMftestlistenselectcharbg, DoTestActivity.this, DeviceUtils.dip2px(DoTestActivity.this, 298), DeviceUtils.dip2px(DoTestActivity.this, 90)));
        if (StringUtils.isEmpty(mTestList.get(mPosition).getMfTestListenSelectChar().getName())) {
            tvChar.setText("");
            tvChartwo.setText("");
        } else {
            String chars[] = mTestList.get(mPosition).getMfTestListenSelectChar().getName().split("@");
            if (chars.length < 2) {
                tvChar.setText(chars[0]);
                tvChartwo.setText("");
            } else {
                tvChar.setText(chars[0]);
                tvChartwo.setText(chars[1]);
            }
        }
        tvNeedchar.setText("");
        if (null != mMusicTestService && null != mMusicTestService.player) {
            mMusicTestService.stop();
        }
        mMusicTestService = new MusicTestService(mTestList.get(mPosition).getMfTestListenSelectChar().getAudio(), DoTestActivity.this);
        List<String> wordList = new ArrayList<>();
        wordList.add(mTestList.get(mPosition).getMfTestListenSelectChar().getAnswerA());
        wordList.add(mTestList.get(mPosition).getMfTestListenSelectChar().getAnswerB());
        wordList.add(mTestList.get(mPosition).getMfTestListenSelectChar().getAnswerC());
        wordList.add(mTestList.get(mPosition).getMfTestListenSelectChar().getAnswerD());
        TestListenSelectCharAdapter adapter = new TestListenSelectCharAdapter(DoTestActivity.this, wordList);
        gvMftestlistenselectchar.setAdapter(adapter);
        gvMftestlistenselectchar.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (((position + 1) + "").equals(mTestList.get(mPosition).getMfTestListenSelectChar().getAnswerKey())) {//答对
                    tvNeedchar.setText(wordList.get(position));
                    playMusicFromLocal(R.raw.sure, true, mPosition, size, mTestList);
                    //弹出个显示gif图的
                    ivSuccessgif.setVisibility(View.VISIBLE);
                } else {
                    playMusicFromLocal(R.raw.fail, false, mPosition, size, mTestList);
                }
            }
        });

    }

    //听声音选择图片
    private void testListenSelectPic(List<TestBean> mTestList, int mPosition, int size) {
        changeUi(0);
        if (null != mMusicTestService && null != mMusicTestService.player) {
            mMusicTestService.stop();
        }
        mMusicTestService = new MusicTestService(mTestList.get(mPosition).getMfTestListenSelectPic().getAudio(), DoTestActivity.this);
        //得到音频
        List<String> imageUrl = new ArrayList<>();
        imageUrl.add(mTestList.get(mPosition).getMfTestListenSelectPic().getAnswerA());
        imageUrl.add(mTestList.get(mPosition).getMfTestListenSelectPic().getAnswerB());
        imageUrl.add(mTestList.get(mPosition).getMfTestListenSelectPic().getAnswerC());
        imageUrl.add(mTestList.get(mPosition).getMfTestListenSelectPic().getAnswerD());
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        layoutManager.setMeasurementCacheEnabled(true);
        rvMftestlistenselectpic.setLayoutManager(layoutManager);
        rvMftestlistenselectpic.addItemDecoration(new PicDividerGridItemDecoration(this, 30, getResources().getColor(R.color.transparent)));
        TestListenSelectPicAdapter adapter = new TestListenSelectPicAdapter(DoTestActivity.this, imageUrl);
        rvMftestlistenselectpic.setAdapter(adapter);
        adapter.setListener(new ReadDetailTypeListener() {
            @Override
            public void callBack(int position) {
                if (((position + 1) + "").equals(mTestList.get(mPosition).getMfTestListenSelectPic().getAnswerKey())) {//答对
                    playMusicFromLocal(R.raw.sure, true, mPosition, size, mTestList);
                    //弹出个显示gif图的
                    ivSuccessgif.setVisibility(View.VISIBLE);
                    //然后等图关掉  在走下一个
                } else {//答错
                    playMusicFromLocal(R.raw.fail, false, mPosition, size, mTestList);
                }
            }
        });
    }

    public void playMusicFromLocal(int voiceId, boolean isSuccess, int position, int size, List<TestBean> mTestList) {
        if (null != mp && mp.isPlaying()) {
            mp.stop();
            mp.reset();
            mp.release();
        }
        if (null != mMusicTestService && null != mMusicTestService.player && mMusicTestService.player.isPlaying()) {
            mMusicTestService.pause();
        }
        try {
            mp = MediaPlayer.create(this, voiceId);
            mp.start();
            if (isSuccess) {
                mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        //关闭图片  并走下一个
                        ivSuccessgif.setVisibility(View.GONE);
                        currentPosition = selectIndex(position, size);
                        if (currentPosition == -1) {
                            initPostTime(mTestList, currentPosition);
                        } else {
                            selectUi(mTestList, currentPosition, size);
                        }
                    }
                });
            }
        } catch (Exception e) {
            Log.e("DEBUG_TAG", "Player failed", e);
        }
    }

    //提交做题时间
    private void initPostTime(List<TestBean> mTestList, int mPosition) {
        if (null == MoreFunApplication.loginBean.getResult().getOrgan()) {
            return;
        }
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.SAVETESTTIME);
        RequestTestTimeBean requestTestTimeBean = new RequestTestTimeBean();
        RequestTestTimeBean.UserBean userBean = new RequestTestTimeBean.UserBean();
        userBean.setId(mSPutils.getString(Configuration.USERID));
        RequestTestTimeBean.TestBean testBean = new RequestTestTimeBean.TestBean();
        testBean.setId(mTestList.get(0).getMfTest().getId());
        RequestTestTimeBean.OrganBean organBean = new RequestTestTimeBean.OrganBean();
        organBean.setId(MoreFunApplication.loginBean.getResult().getOrgan().getId());
        requestTestTimeBean.setCostSecond(second + "");
        requestTestTimeBean.setOrgan(organBean);
        requestTestTimeBean.setTest(testBean);
        requestTestTimeBean.setUser(userBean);
        params.setBodyContent(JSON.toJSONString(requestTestTimeBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        //这里成功提取时间， 弹出花花的接口
                        if (!StringUtils.isEmpty(getIntent().getStringExtra("BOOKID"))) {
                            mSendStartOrFlowerNet = new SendStarOrFlowerNet(DoTestActivity.this, lyContent);
                            mSendStartOrFlowerNet.initGetFlower(20
                                    , mSPutils.getString(Configuration.USERID),
                                    getIntent().getStringExtra("BOOKID"),
                                    "1", "3"
                            );
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(DoTestActivity.this);
                    errorPop.showPop("");
                    break;
                case 100:
                    ListViewUtil.setListViewHeightBasedOnChildren(lvMftestpicselect, R.layout.layout_testpicselect, DoTestActivity.this);
                    break;
            }
        }
    };

    private int selectIndex(int position, int size) {
        int mPosition = 0;
        if (position == (size - 1)) {
            mPosition = -1;
        } else {
            mPosition = position + 1;
        }
        return mPosition;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            isBreak = true;
            if (null != mSendStartOrFlowerNet) {
                mSendStartOrFlowerNet.stopAnim();
            }
            if (null != mMusicTestService) {
                mMusicTestService.stop();
            }
            MoreFunApplication.isOut = true;//退出
            if (null != mp) {
                mp.stop();
                mp.reset();
                mp.release();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void changeUi(int index) {
        switch (index) {
            case 0:
                llMftestlistenselectpic.setVisibility(View.VISIBLE);
                llMftestlistenselectchar.setVisibility(View.GONE);
                llMftesttextselect.setVisibility(View.GONE);
                llMftestlistenword.setVisibility(View.GONE);
                llMftestpicselect.setVisibility(View.GONE);
                break;
            case 1:
                llMftestlistenselectpic.setVisibility(View.GONE);
                llMftestlistenselectchar.setVisibility(View.VISIBLE);
                llMftesttextselect.setVisibility(View.GONE);
                llMftestlistenword.setVisibility(View.GONE);
                llMftestpicselect.setVisibility(View.GONE);
                break;
            case 2:
                llMftestlistenselectpic.setVisibility(View.GONE);
                llMftestlistenselectchar.setVisibility(View.GONE);
                llMftesttextselect.setVisibility(View.VISIBLE);
                llMftestlistenword.setVisibility(View.GONE);
                llMftestpicselect.setVisibility(View.GONE);
                break;
            case 3:
                llMftestlistenselectpic.setVisibility(View.GONE);
                llMftestlistenselectchar.setVisibility(View.GONE);
                llMftesttextselect.setVisibility(View.GONE);
                llMftestlistenword.setVisibility(View.VISIBLE);
                llMftestpicselect.setVisibility(View.GONE);
                break;
            case 4:
                llMftestlistenselectpic.setVisibility(View.GONE);
                llMftestlistenselectchar.setVisibility(View.GONE);
                llMftesttextselect.setVisibility(View.GONE);
                llMftestlistenword.setVisibility(View.GONE);
                llMftestpicselect.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    protected void initData() {

    }


    @OnClick({R.id.iv_back, R.id.iv_mftestlistenselectpic, R.id.iv_mftestlistenselectchar, R.id.ll_listentext, R.id.iv_mftestlistenword})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                BackIdeaPop pop = new BackIdeaPop(DoTestActivity.this);
                pop.showPop("确定退出当前页面吗？", 4, 0);
                break;
            case R.id.iv_mftestlistenselectpic://播放
                //
                try {
                    if (null != mMusicTestService && null != mMusicTestService.player) {
                        if (!mMusicTestService.player.isPlaying()) {
//                            if (null != mp) {
//                                mp.stop();
//                                mp.reset();
//                                mp.release();
//                            }
                            mMusicTestService.play();
                        } else {
                            mMusicTestService.pause();
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case R.id.iv_mftestlistenselectchar://播放
                try {
                    if (null != mMusicTestService && null != mMusicTestService.player) {
                        if (!mMusicTestService.player.isPlaying()) {
//                            if (null != mp) {
//                                mp.stop();
//                                mp.reset();
//                                mp.release();
//                            }
                            mMusicTestService.play();
                        } else {
                            mMusicTestService.pause();
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case R.id.ll_listentext://播放
                try {
                    if (!StringUtils.isEmpty(picSelectUrl)) {
                        if (null != mMusicTestService && null != mMusicTestService.player) {
                            mMusicTestService = new MusicTestService(picSelectUrl, DoTestActivity.this);
                            if (!mMusicTestService.player.isPlaying()) {
//                                if (null != mp) {
//                                    mp.stop();
//                                    mp.reset();
//                                    mp.release();
//                                }
                                mMusicTestService.play();
                            } else {
                                mMusicTestService.pause();
                            }
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case R.id.iv_mftestlistenword:
                try {
                    if (null != mMusicTestService && null != mMusicTestService.player) {
                        if (!mMusicTestService.player.isPlaying()) {
//                            if (null != mp) {
//                                mp.stop();
//                                mp.reset();
//                                mp.release();
//                            }
                            mMusicTestService.play();
                        } else {
                            mMusicTestService.pause();
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
        }
    }
}
